﻿using System.Security.Cryptography;
using System.Text;

namespace tools.algorithm
{
    /// <summary>
    /// SHA-256 工具类（安全哈希算法）
    /// </summary>
    public static class Sha256Tool
    {
        /// <summary>
        /// 使用 SHA-256 算法计算字符串的哈希值
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>64 个十六进制字符</returns>
        public static string GetHash(string? str)
        {
            if (string.IsNullOrWhiteSpace(str))
            {
                return string.Empty;
            }

            byte[] bytes = SHA256.HashData(Encoding.UTF8.GetBytes(str));

            var sb = new StringBuilder();
            foreach (var item in bytes)
            {
                sb.Append(item.ToString("x2")); // 转小写十六进制
            }

            return sb.ToString();
        }

        /// <summary>
        /// 验证哈希是否由指定的字符串使用 SHA-256 算法生成
        /// </summary>
        /// <param name="hash">字符串的哈希</param>
        /// <param name="str">字符串</param>
        /// <returns>是则返回 true，反之返回 false</returns>
        public static bool VerifyHash(string? hash, string? str)
        {
            return GetHash(str) == hash;
        }

        /// <summary>
        ///使用 SHA-256 算法计算文件流的哈希值
        /// </summary>
        /// <param name="stream">文件流</param>
        /// <returns>64 个十六进制字符</returns>
        public static string GetHash(Stream? stream)
        {
            ArgumentNullException.ThrowIfNull(stream);
            stream.Position = 0;

            using var sha256 = SHA256.Create();
            byte[] bytes = sha256.ComputeHash(stream);
            return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLower();
        }

        /// <summary>
        /// 验证哈希是否由指定的文件流使用 SHA-256 算法生成
        /// </summary>
        /// <param name="hash">文件流的哈希</param>
        /// <param name="stream">文件流</param>
        /// <returns>是则返回 true，反之返回 false</returns>
        public static bool VerifyHash(string? hash, Stream? stream)
        {
            return GetHash(stream) == hash;
        }
    }
}
